<template>
    <div class="circle-manage-page">
        <!-- 主内容区域 -->
        <div class="main-content">
            <!-- 右侧内容区域 -->
            <main class="manage-main">
                <div class="manage-container">
                    <!-- 页面标题和操作按钮 -->
                    <div class="page-header">
                        <h1 class="page-title">圈子管理</h1>
                        <el-button type="primary" @click="handleCreateCircle">
                            <el-icon>
                                <Plus />
                            </el-icon>
                            新增圈子
                        </el-button>
                    </div>

                    <!-- 搜索和筛选区域 -->
                    <div class="filter-section">
                        <div class="search-group">
                            <el-select v-model="searchType" placeholder="搜索类型" style="width: 120px">
                                <el-option label="圈子名称" value="name" />
                                <el-option label="圈子类型" value="type" />
                                <el-option label="全部" value="both" />
                            </el-select>
                            <el-input v-model="searchKeyword" placeholder="搜索圈子..." class="search-input"
                                @keyup.enter="handleSearch" clearable @clear="handleClearSearch">
                                <template #prefix>
                                    <el-icon>
                                        <Search />
                                    </el-icon>
                                </template>
                            </el-input>
                            <el-button type="primary" @click="handleSearch" :loading="loading">
                                搜索
                            </el-button>
                        </div>
                    </div>

                    <!-- 圈子列表表格 -->
                    <div class="table-section">
                        <el-table :data="circles" v-loading="loading" style="width: 100%">
                            <el-table-column prop="circle_id" label="ID" width="80" />
                            <el-table-column prop="name" label="圈子名称" min-width="120" />
                            <el-table-column prop="type" label="类型" width="120" />
                            <el-table-column prop="description" label="描述" min-width="200"
                                :show-overflow-tooltip="true" />
                            <el-table-column prop="member_count" label="成员数" width="100" align="center">
                                <template #default="{ row }">
                                    <el-button type="primary" link @click="showCircleMembers(row.circle_id)">
                                        {{ row.member_count }}
                                    </el-button>
                                </template>
                            </el-table-column>
                            <el-table-column prop="post_count" label="帖子数" width="100" align="center" />
                            <el-table-column label="创建时间" width="180">
                                <template #default="{ row }">
                                    {{ formatTime(row.created_at) }}
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="240" fixed="right">
                                <template #default="{ row }">
                                    <el-button type="primary" size="small" @click="handleEditCircle(row)">
                                        编辑
                                    </el-button>
                                    <el-button type="info" size="small" @click="showCircleMembers(row.circle_id)">
                                        成员
                                    </el-button>
                                    <el-button type="danger" size="small" @click="handleDeleteCircle(row.circle_id)"
                                        :loading="row.deleting">
                                        删除
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>

                    <!-- 分页组件 -->
                    <div v-if="circles.length > 0" class="pagination-section">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[10, 20, 50, 100]" :small="false" :disabled="false" :background="true"
                            layout="total, sizes, prev, pager, next, jumper" :total="total"
                            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
                    </div>
                </div>
            </main>
        </div>

        <!-- 新增/编辑圈子模态框 -->
        <el-dialog v-model="circleDialogVisible" :title="circleDialogTitle" width="600px"
            :before-close="handleCloseDialog">
            <el-form ref="circleFormRef" :model="circleForm" :rules="circleRules" label-width="80px">
                <el-form-item label="圈子名称" prop="name">
                    <el-input v-model="circleForm.name" placeholder="请输入圈子名称" maxlength="50" show-word-limit />
                </el-form-item>
                <el-form-item label="圈子类型" prop="type">
                    <el-input v-model="circleForm.type" placeholder="请输入圈子类型" maxlength="20" show-word-limit />
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input v-model="circleForm.description" type="textarea" :rows="4" placeholder="请输入圈子描述"
                        maxlength="200" show-word-limit />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleCloseDialog">取消</el-button>
                    <el-button type="primary" @click="handleSubmitCircle" :loading="submitting">
                        确定
                    </el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 圈子成员模态框 -->
        <el-dialog v-model="membersDialogVisible" title="圈子成员" width="1000px" :before-close="handleCloseMembersDialog">
            <div class="members-section">
                <div class="members-header">
                    <h3>圈子: {{ currentCircle?.name }}</h3>
                    <span class="member-count">共 {{ circleMembers.length }} 名成员</span>
                </div>
                <el-table :data="circleMembers" height="400" v-loading="membersLoading">
                    <el-table-column label="头像" width="80">
                        <template #default="scope">
                            <el-avatar :src="scope.row.avatar" :size="50" fit="cover">
                                <img src="@/assets/default-avatar.png" alt="默认头像" />
                            </el-avatar>
                        </template>
                    </el-table-column>
                    <el-table-column prop="user_id" label="用户ID" width="80" />
                    <el-table-column label="昵称" min-width="120">
                        <template #default="{ row }">
                            {{ row.nickname ? row.nickname : '未设置昵称' }}
                        </template>
                    </el-table-column>

                    <el-table-column prop="phone" label="手机号" min-width="120" />
                    <el-table-column prop="email" label="邮箱" min-width="160" />
                    <el-table-column prop="joined_at" label="加入时间" width="180">
                        <template #default="{ row }">
                            {{ formatTime(row.joined_at) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120" fixed="right">
                        <template #default="{ row }">
                            <el-button type="danger" size="small" @click="handleRemoveMember(row.user_id)"
                                :loading="row.removing">
                                移除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { useCirclesStore } from '@/stores/circles'

const router = useRouter()
const circlesStore = useCirclesStore()

// 响应式数据
const searchKeyword = ref('')
const searchType = ref('name')
const loading = ref(false)
const isSearching = ref(false)
const activeSidebar = ref('admin')
const submitting = ref(false)

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 圈子列表
const circles = ref([])

// 模态框相关
const circleDialogVisible = ref(false)
const membersDialogVisible = ref(false)
const circleFormRef = ref(null)
const circleForm = ref({
    name: '',
    type: '',
    description: ''
})
const isEditing = ref(false)
const editingCircleId = ref(null)

// 成员相关
const currentCircle = ref(null)
const circleMembers = ref([])
const membersLoading = ref(false)

// 计算对话框标题
const circleDialogTitle = computed(() => {
    return isEditing.value ? '编辑圈子' : '新增圈子'
})

// 表单验证规则
const circleRules = {
    name: [
        { required: true, message: '请输入圈子名称', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请输入圈子类型', trigger: 'blur' },
        { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入圈子描述', trigger: 'blur' },
        { min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
    ]
}

// 初始化加载
onMounted(() => {
    fetchCircles()
})

// 监听分页变化
watch([currentPage, pageSize], () => {
    if (!isSearching.value) {
        fetchCircles()
    } else {
        handleSearch()
    }
})

// 获取圈子列表
const fetchCircles = async () => {
    try {
        loading.value = true
        const response = await circlesStore.fetchCirclesAction({
            page: currentPage.value,
            pageSize: pageSize.value
        })
        if (response.code === 0) {
            circles.value = response.data.list || []
            total.value = response.data.pagination?.total || circles.value.length
        }
    } catch (error) {
        ElMessage.error('获取圈子列表失败：' + error.message)
    } finally {
        loading.value = false
    }
}

// 搜索圈子
const handleSearch = async () => {
    if (!searchKeyword.value.trim()) {
        ElMessage.warning('请输入搜索关键词')
        return
    }

    try {
        loading.value = true
        isSearching.value = true
        currentPage.value = 1

        const response = await circlesStore.searchCirclesAction(searchKeyword.value.trim(), {
            page: currentPage.value,
            pageSize: pageSize.value,
            searchType: searchType.value
        })
        if (response.code === 0) {
            circles.value = response.data.list || []
            total.value = response.data.pagination?.total || circles.value.length

            const searchTypeText = {
                'name': '圈子名称',
                'type': '圈子类型',
                'both': '全部'
            }[searchType.value]

            ElMessage.success(`在${searchTypeText}中找到 ${total.value} 个相关圈子`)
        }
    } catch (error) {
        ElMessage.error('搜索失败：' + error.message)
    } finally {
        loading.value = false
    }
}

// 清空搜索
const handleClearSearch = () => {
    searchKeyword.value = ''
    searchType.value = 'name'
    isSearching.value = false
    currentPage.value = 1
    fetchCircles()
}

// 每页条数变化
const handleSizeChange = (newSize) => {
    pageSize.value = newSize
    currentPage.value = 1
}

// 当前页变化
const handleCurrentChange = (newPage) => {
    currentPage.value = newPage
}

// 新增圈子
const handleCreateCircle = () => {
    isEditing.value = false
    editingCircleId.value = null
    circleForm.value = {
        name: '',
        type: '',
        description: ''
    }
    circleDialogVisible.value = true
}

// 编辑圈子
const handleEditCircle = (circle) => {
    isEditing.value = true
    editingCircleId.value = circle.circle_id
    circleForm.value = {
        name: circle.name,
        type: circle.type,
        description: circle.description
    }
    circleDialogVisible.value = true
}

// 提交圈子表单
const handleSubmitCircle = async () => {
    if (!circleFormRef.value) return

    try {
        await circleFormRef.value.validate()
        submitting.value = true

        if (isEditing.value) {
            // 编辑圈子
            const response = await circlesStore.updateCircleAction(editingCircleId.value, circleForm.value)
            if (response.code === 0) {
                ElMessage.success('更新圈子成功')
                circleDialogVisible.value = false
                fetchCircles()
            }
        } else {
            // 新增圈子
            const response = await circlesStore.createCircleAction(circleForm.value)
            if (response.code === 0) {
                ElMessage.success('创建圈子成功')
                circleDialogVisible.value = false
                fetchCircles()
            }
        }
    } catch (error) {
        if (error.errors) {
            ElMessage.warning('请完善表单信息')
        } else {
            ElMessage.error((isEditing.value ? '更新' : '创建') + '圈子失败：' + error.message)
        }
    } finally {
        submitting.value = false
    }
}
// 删除圈子
const handleDeleteCircle = async (circleId) => {
    try {
        await ElMessageBox.confirm('确定要删除这个圈子吗？此操作不可恢复。', '确认删除', {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        })

        const circle = circles.value.find(c => c.circle_id === circleId)
        if (circle) {
            circle.deleting = true
        }

        const response = await circlesStore.deleteCircleAction(circleId)
        if (response.code === 0) {
            ElMessage.success('删除圈子成功')
            fetchCircles()
        }
    } catch (error) {
        if (error === 'cancel') {
            ElMessage.info('已取消删除')
        } else {
            ElMessage.error('删除圈子失败：' + error.message)
        }
    } finally {
        const circle = circles.value.find(c => c.circle_id === circleId)
        if (circle) {
            circle.deleting = false
        }
    }
}

// 显示圈子成员
const showCircleMembers = async (circleId) => {
    try {
        membersLoading.value = true
        currentCircle.value = circles.value.find(c => c.circle_id === circleId)

        const response = await circlesStore.fetchCircleMembersAction(circleId)
        if (response.code === 0) {
            circleMembers.value = response.data.list || response.data
            membersDialogVisible.value = true
        }
    } catch (error) {
        ElMessage.error('获取圈子成员失败：' + error.message)
    } finally {
        membersLoading.value = false
    }
}

// 移除成员（管理员强制移除）
const handleRemoveMember = async (userId) => {
    try {
        await ElMessageBox.confirm('确定要将此成员移出圈子吗？', '确认移除', {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        })

        const member = circleMembers.value.find(m => m.user_id === userId)
        if (member) {
            member.removing = true
        }

        // 使用正确的移除成员函数
        const response = await circlesStore.removeCircleMemberAction(
            currentCircle.value.circle_id,
            userId
        )

        if (response.code === 0) {
            ElMessage.success('移除成员成功')
            // 直接从本地列表中移除，避免重新加载
            circleMembers.value = circleMembers.value.filter(member => member.user_id !== userId)
        }
    } catch (error) {
        if (error === 'cancel') {
            ElMessage.info('已取消移除')
        } else {
            ElMessage.error('移除成员失败：' + error.message)
        }
    } finally {
        const member = circleMembers.value.find(m => m.user_id === userId)
        if (member) {
            member.removing = false
        }
    }
}
// 关闭对话框
const handleCloseDialog = () => {
    circleDialogVisible.value = false
    circleFormRef.value?.clearValidate()
}

// 关闭成员对话框
const handleCloseMembersDialog = () => {
    membersDialogVisible.value = false
    circleMembers.value = []
    currentCircle.value = null
}

// 格式化时间
const formatTime = (timeString) => {
    if (!timeString) return ''
    return new Date(timeString).toLocaleString('zh-CN')
}
</script>

<style scoped>
.circle-manage-page {
    min-height: 100vh;
    background-color: #f5f7fa;
    display: flex;
    flex-direction: column;
}

/* 主内容区域 */
.main-content {
    display: flex;
    flex: 1;
    overflow: hidden;
}

.manage-main {
    flex: 1;
    padding: 20px;
    overflow-y: auto;
    margin-left: 20px;
}

.manage-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 页面标题 */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e4e7ed;
}

.page-title {
    margin: 0;
    color: #303133;
    font-size: 24px;
    font-weight: 600;
}

/* 筛选区域 */
.filter-section {
    margin-bottom: 20px;
}

.search-group {
    display: flex;
    gap: 12px;
    align-items: center;
}

.search-input {
    width: 300px;
}

/* 表格区域 */
.table-section {
    margin-bottom: 24px;
}

/* 分页 */
.pagination-section {
    display: flex;
    justify-content: center;
    padding-top: 16px;
    border-top: 1px solid #e4e7ed;
}

/* 成员管理 */
.members-section {
    padding: 0 10px;
}

.members-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #e4e7ed;
}

.members-header h3 {
    margin: 0;
    color: #303133;
}

.member-count {
    color: #606266;
    font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .manage-main {
        margin-left: 240px;
        padding: 16px;
    }

    .manage-container {
        padding: 16px;
    }

    .page-header {
        flex-direction: column;
        gap: 16px;
        align-items: stretch;
    }

    .search-group {
        flex-direction: column;
        align-items: stretch;
    }

    .search-input {
        width: 100%;
    }
}
</style>